#include "deepseek_chat.h"
#include "getWeatherData.h"

// 全局变量用于存储接收到的回答内容
char recvive_buffer[4096*2]={0};
void process_escape_chars(char *str) 
{
    int i = 0, j = 0;
    int len = strlen(str);
    
    while (i < len) {
        if (str[i] == '\\' && i + 1 < len) {
            switch (str[i + 1]) {
                case 'n':
                    str[j++] = '\n';
                    i += 2;
                    break;
                case 't':
                    str[j++] = '\t';
                    i += 2;
                    break;
                case 'r':
                    str[j++] = '\r';
                    i += 2;
                    break;
                case '"':
                    str[j++] = '"';
                    i += 2;
                    break;
                case '\\':
                    str[j++] = '\\';
                    i += 2;
                    break;
                default:
                    str[j++] = str[i++];
                    break;
            }
        } else {
            str[j++] = str[i++];
        }
    }
    str[j] = '\0';
}

// 简化的接收和解析函数
int receive_http_response(SSL *ssl) 
{
    char response[BUFFER_SIZE];
    char total_response[BUFFER_SIZE * 8] = {0};
    int total_bytes = 0;
    int bytes_read;
    
    printf("服务器响应:\n");
    printf("========================================\n");
    
    // 读取所有数据
    do 
    {
        bytes_read = SSL_read(ssl, response, BUFFER_SIZE - 1);
        if (bytes_read > 0) 
        {
            response[bytes_read] = '\0';
            printf("%s", response);
            
            if (total_bytes + bytes_read < sizeof(total_response)) 
            {
                strcat(total_response, response);
                total_bytes += bytes_read;
            }
        } 
    } while (bytes_read > 0);

    printf("\n开始解析数据....\n");
    
    // 直接在整个响应中搜索content
    char *content_start = strstr(total_response, "\"content\":\"");
    if (content_start != NULL) 
    {
        content_start += 11; // 跳过"content":"
        
        char *content_end = strstr(content_start, "\",\"logprobs\"");
        if (content_end == NULL) {
            content_end = strstr(content_start, "\",\"finish_reason\"");
        }
        if (content_end == NULL) {
            content_end = strstr(content_start, "\"},");
        }
        
        if (content_end != NULL) 
        {
            int content_len = content_end - content_start;
            if (content_len < sizeof(recvive_buffer)) 
            {
                strncpy(recvive_buffer, content_start, content_len);
                recvive_buffer[content_len] = '\0';
                
                // 处理转义字符
                process_escape_chars(recvive_buffer);
                
                printf("\n\n提取的回答内容:\n%s\n", recvive_buffer);
            }
        }
    }
    
    printf("\n========================================\n");
    printf("总共接收字节数: %d\n", total_bytes);
    return total_bytes;
}



// 解析出deepseek返回的数据
int chat_with_bot(char *message) 
{
    char web_addr[] = "api.deepseek.com";
    char URL[] = "/v1/chat/completions";
    

    printf("目标地址: https://%s%s\n", web_addr, URL);
    
    // 域名解析
    struct hostent *hostinfo = gethostbyname(web_addr);
    if(hostinfo == NULL) {
        perror("域名解析失败");
        return -1;
    }

    char server_ip[20];
    strcpy(server_ip, inet_ntoa(*(struct in_addr *)(hostinfo->h_addr_list[0])));
    printf("服务器IP: %s\n", server_ip);
    
    // TCP连接
    int skt_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(skt_fd == -1) {
        perror("创建socket失败");
        return -1;
    }
    
    struct sockaddr_in addrinfo;
    addrinfo.sin_family = AF_INET;
    addrinfo.sin_port = htons(443);
    addrinfo.sin_addr.s_addr = inet_addr(server_ip);
    
    if(connect(skt_fd, (struct sockaddr *)&addrinfo, sizeof(addrinfo)) == -1) {
        perror("连接服务器失败");
        close(skt_fd);
        return -1;
    }
    
    printf("TCP连接服务器成功\n");

    // SSL加密
    SSL *ssl;
    SSL_CTX *ctx;
    if(init_SSL(skt_fd, &ssl, &ctx) == -1) {
        perror("SSL初始化失败");
        close(skt_fd);
        return -1;
    }

    printf("SSL连接建立成功\n");

    // 构建DeepSeek API请求
    char api_key[] = "aaaa"; // 替换为你的实际API密钥
    char json_body[512];
    // char message[] = "你好，请介绍一下你自己";
    
    snprintf(json_body, sizeof(json_body),
        "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}]}",
        message);

    // 发送HTTP POST请求
    char request_cmd[1024];
    snprintf(request_cmd, sizeof(request_cmd),
        "POST %s HTTP/1.1\r\n"
        "Host: %s\r\n"
        "Authorization: Bearer %s\r\n"
        "Content-Type: application/json\r\n"
        "Content-Length: %ld\r\n"
        "Connection: close\r\n"
        "\r\n"
        "%s",
        URL, web_addr, api_key, strlen(json_body), json_body);

    printf("发送请求到DeepSeek API...\n");
    
    if(SSL_write(ssl, request_cmd, strlen(request_cmd)) <= 0) {
        perror("发送请求失败");
        destroy_SSL(ssl, ctx);
        close(skt_fd);
        return -1;
    }

    printf("HTTP请求已发送\n");

    // 接收响应
    receive_http_response(ssl);

    // 清理资源
    destroy_SSL(ssl, ctx);
    close(skt_fd);
    
    printf("程序执行完成\n");

    return 0;
}